package com.security.sdk.provider;

import com.security.sdk.entity.RoleEntity;
import com.security.sdk.entity.UserEntity;
import com.security.sdk.service.RoleService;
import com.security.sdk.service.UserService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 自定义登录验证
 * @Author lhc
 * @CreateTime 2020/10/1 19:11
 */
@Component
public class UserAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        // 获取表单输入中返回的用户名
        String loginName = (String) authentication.getPrincipal();

        // 获取表单中输入的密码
        String password = (String) authentication.getCredentials();

        // 查询用户是否存在
        UserEntity userInfo = userService.getUserInfo(loginName);

        if(Objects.isNull(userInfo)){
            throw new UsernameNotFoundException("用户不存在");
        }

        // 我们还要判断密码是否正确，这里我们的密码使用BCryptPasswordEncoder进行加密的
        if (!new BCryptPasswordEncoder().matches(password, userInfo.getPassword())) {
            throw new BadCredentialsException("密码不正确");
        }

        // 还可以加一些其他信息的判断，比如用户账号已停用等判断

        // 角色集合
        Set<GrantedAuthority> authorities = new HashSet<>();

        // 查询用户角色
        List<RoleEntity> rolesInfo = roleService.getRolesInfo(userInfo.getUserId());

        for (RoleEntity roleEntity: rolesInfo){
            authorities.add(new SimpleGrantedAuthority("ROLE_" + roleEntity.getRoleName()));
        }
        userInfo.setAuthorities(authorities);

        // 进行登录
        return new UsernamePasswordAuthenticationToken(userInfo, password, authorities);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
